#!/usr/bin/env python3
"""
固定资产管理系统功能演示脚本
展示系统的主要功能和特性
"""

import os
import sys
import django
import random
from datetime import datetime, timedelta

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'asset_management.settings')
django.setup()

from django.contrib.auth.models import User
from django.utils import timezone
from assets.models import *
from assets.models_system import *
from assets.models_transfer import *
from assets.models_ai import *


class SystemDemo:
    def __init__(self):
        self.demo_data = {}
        
    def print_header(self, title):
        """打印标题"""
        print("\n" + "="*60)
        print(f"🎯 {title}")
        print("="*60)
    
    def print_section(self, title):
        """打印章节"""
        print(f"\n📋 {title}")
        print("-"*40)
    
    def create_demo_users(self):
        """创建演示用户"""
        self.print_section("创建演示用户")
        
        users_data = [
            {'username': 'admin', 'email': 'admin@example.com', 'first_name': '系统', 'last_name': '管理员', 'is_staff': True, 'is_superuser': True},
            {'username': 'manager', 'email': 'manager@example.com', 'first_name': '资产', 'last_name': '管理员', 'is_staff': True},
            {'username': 'user1', 'email': 'user1@example.com', 'first_name': '张', 'last_name': '三'},
            {'username': 'user2', 'email': 'user2@example.com', 'first_name': '李', 'last_name': '四'},
            {'username': 'user3', 'email': 'user3@example.com', 'first_name': '王', 'last_name': '五'},
        ]
        
        created_users = []
        for user_data in users_data:
            user, created = User.objects.get_or_create(
                username=user_data['username'],
                defaults={
                    'email': user_data['email'],
                    'first_name': user_data['first_name'],
                    'last_name': user_data['last_name'],
                    'is_staff': user_data.get('is_staff', False),
                    'is_superuser': user_data.get('is_superuser', False),
                }
            )
            if created:
                user.set_password('demo123456')
                user.save()
                print(f"✓ 创建用户: {user.username} ({user.first_name}{user.last_name})")
            else:
                print(f"✓ 用户已存在: {user.username}")
            created_users.append(user)
        
        self.demo_data['users'] = created_users
        return created_users
    
    def create_demo_organizations(self):
        """创建演示组织架构"""
        self.print_section("创建组织架构")
        
        # 创建组织
        org, created = Organization.objects.get_or_create(
            name='演示科技有限公司',
            defaults={
                'code': 'DEMO',
                'description': '演示用的科技公司'
            }
        )
        if created:
            print(f"✓ 创建组织: {org.name}")
        else:
            print(f"✓ 组织已存在: {org.name}")
        
        # 创建位置
        locations_data = [
            {'name': '总部大楼', 'address': '北京市朝阳区演示大街123号'},
            {'name': '研发中心', 'address': '北京市海淀区科技园区456号'},
            {'name': '生产基地', 'address': '河北省廊坊市工业园区789号'},
        ]
        
        locations = []
        for loc_data in locations_data:
            location, created = Location.objects.get_or_create(
                name=loc_data['name'],
                defaults={'address': loc_data['address']}
            )
            if created:
                print(f"✓ 创建位置: {location.name}")
            locations.append(location)
        
        # 创建部门
        departments_data = [
            {'name': '信息技术部', 'code': 'IT', 'location': locations[0]},
            {'name': '人力资源部', 'code': 'HR', 'location': locations[0]},
            {'name': '财务部', 'code': 'FIN', 'location': locations[0]},
            {'name': '研发部', 'code': 'RD', 'location': locations[1]},
            {'name': '生产部', 'code': 'PROD', 'location': locations[2]},
        ]
        
        departments = []
        for dept_data in departments_data:
            dept, created = Department.objects.get_or_create(
                name=dept_data['name'],
                defaults={
                    'code': dept_data['code'],
                    'organization': org,
                    'location': dept_data['location']
                }
            )
            if created:
                print(f"✓ 创建部门: {dept.name}")
            departments.append(dept)
        
        self.demo_data['organization'] = org
        self.demo_data['locations'] = locations
        self.demo_data['departments'] = departments
        return org, locations, departments
    
    def create_demo_categories_and_assets(self):
        """创建演示资产类别和资产"""
        self.print_section("创建资产类别和资产")
        
        # 创建资产类别
        categories_data = [
            {'name': '计算机设备', 'code': 'COMP', 'description': '台式机、笔记本电脑等'},
            {'name': '办公设备', 'code': 'OFFICE', 'description': '打印机、复印机、投影仪等'},
            {'name': '网络设备', 'code': 'NET', 'description': '路由器、交换机、防火墙等'},
            {'name': '家具设备', 'code': 'FURN', 'description': '办公桌、椅子、柜子等'},
            {'name': '车辆设备', 'code': 'VEH', 'description': '公司车辆'},
        ]
        
        categories = []
        for cat_data in categories_data:
            category, created = AssetCategory.objects.get_or_create(
                name=cat_data['name'],
                defaults={
                    'code': cat_data['code'],
                    'description': cat_data['description']
                }
            )
            if created:
                print(f"✓ 创建资产类别: {category.name}")
            categories.append(category)
        
        # 创建供应商
        suppliers_data = [
            {'name': '联想集团', 'contact_person': '张经理', 'phone': '010-12345678'},
            {'name': '戴尔科技', 'contact_person': '李经理', 'phone': '010-87654321'},
            {'name': '华为技术', 'contact_person': '王经理', 'phone': '010-11223344'},
        ]
        
        suppliers = []
        for sup_data in suppliers_data:
            supplier, created = Supplier.objects.get_or_create(
                name=sup_data['name'],
                defaults={
                    'contact_person': sup_data['contact_person'],
                    'phone': sup_data['phone']
                }
            )
            if created:
                print(f"✓ 创建供应商: {supplier.name}")
            suppliers.append(supplier)
        
        # 创建资产
        assets_data = [
            {'name': 'ThinkPad X1 Carbon', 'category': categories[0], 'price': 12000, 'dept': self.demo_data['departments'][0]},
            {'name': 'Dell OptiPlex 7090', 'category': categories[0], 'price': 8000, 'dept': self.demo_data['departments'][1]},
            {'name': 'MacBook Pro 16"', 'category': categories[0], 'price': 18000, 'dept': self.demo_data['departments'][3]},
            {'name': 'HP LaserJet Pro', 'category': categories[1], 'price': 3000, 'dept': self.demo_data['departments'][0]},
            {'name': '佳能复印机', 'category': categories[1], 'price': 15000, 'dept': self.demo_data['departments'][1]},
            {'name': '华为交换机', 'category': categories[2], 'price': 5000, 'dept': self.demo_data['departments'][0]},
            {'name': '办公桌椅套装', 'category': categories[3], 'price': 2000, 'dept': self.demo_data['departments'][2]},
            {'name': '会议室投影仪', 'category': categories[1], 'price': 8000, 'dept': self.demo_data['departments'][0]},
        ]
        
        assets = []
        for i, asset_data in enumerate(assets_data, 1):
            asset_number = f"AS{datetime.now().year}{i:04d}"
            asset, created = Asset.objects.get_or_create(
                asset_number=asset_number,
                defaults={
                    'name': asset_data['name'],
                    'category': asset_data['category'],
                    'department': asset_data['dept'],
                    'location': asset_data['dept'].location,
                    'user': random.choice(self.demo_data['users'][2:]),  # 随机分配给普通用户
                    'supplier': random.choice(suppliers),
                    'purchase_date': timezone.now().date() - timedelta(days=random.randint(30, 365)),
                    'purchase_price': asset_data['price'],
                    'depreciation_rate': random.uniform(5, 15),
                    'status': random.choice(['idle', 'in_use']),
                    'description': f'演示用{asset_data["name"]}'
                }
            )
            if created:
                print(f"✓ 创建资产: {asset.name} ({asset.asset_number})")
            assets.append(asset)
        
        self.demo_data['categories'] = categories
        self.demo_data['suppliers'] = suppliers
        self.demo_data['assets'] = assets
        return categories, suppliers, assets
    
    def create_demo_business_data(self):
        """创建演示业务数据"""
        self.print_section("创建业务流程数据")
        
        # 创建维修记录
        for asset in random.sample(self.demo_data['assets'], 3):
            maintenance = MaintenanceRecord.objects.create(
                asset=asset,
                maintenance_type='preventive',
                title=f'{asset.name}定期维护',
                description='定期维护保养，检查设备运行状态',
                reporter=random.choice(self.demo_data['users']),
                technician=self.demo_data['users'][1],  # manager作为技师
                estimated_cost=random.uniform(200, 1000),
                status='completed',
                completed_at=timezone.now() - timedelta(days=random.randint(1, 30))
            )
            print(f"✓ 创建维修记录: {maintenance.title}")
        
        # 创建借用记录
        for asset in random.sample(self.demo_data['assets'], 2):
            borrow = AssetBorrow.objects.create(
                asset=asset,
                borrower=random.choice(self.demo_data['users'][2:]),
                purpose='work',
                purpose_description='临时工作需要使用',
                expected_return_date=timezone.now() + timedelta(days=7),
                status='borrowed',
                approved_at=timezone.now() - timedelta(hours=2),
                approver=self.demo_data['users'][1]
            )
            print(f"✓ 创建借用记录: {borrow.asset.name}")
        
        # 创建调拨记录
        transfer = AssetTransfer.objects.create(
            title='IT设备部门调拨',
            transfer_type='department',
            reason='部门重组，需要重新分配IT设备',
            applicant=self.demo_data['users'][1],
            applicant_department=self.demo_data['departments'][0],
            target_department=self.demo_data['departments'][3],
            priority='medium',
            expected_completion_date=timezone.now() + timedelta(days=5),
            status='pending'
        )
        
        # 添加调拨项目
        for asset in random.sample(self.demo_data['assets'][:3], 2):
            AssetTransferItem.objects.create(
                transfer=transfer,
                asset=asset
            )
        
        print(f"✓ 创建调拨申请: {transfer.title}")
        
        # 创建盘点计划
        inventory_plan = InventoryPlan.objects.create(
            name='2025年第一季度资产盘点',
            plan_type='full',
            planned_start_date=timezone.now() + timedelta(days=1),
            planned_end_date=timezone.now() + timedelta(days=7),
            creator=self.demo_data['users'][1],
            description='全面盘点公司所有固定资产'
        )
        inventory_plan.assignees.add(*self.demo_data['users'][2:4])
        inventory_plan.departments.add(*self.demo_data['departments'][:3])
        
        # 添加盘点项目
        for asset in self.demo_data['assets'][:5]:
            InventoryItem.objects.create(
                plan=inventory_plan,
                asset=asset,
                system_status=asset.status,
                system_location=asset.location,
                system_user=asset.user,
                system_department=asset.department
            )
        
        print(f"✓ 创建盘点计划: {inventory_plan.name}")
    
    def create_demo_ai_data(self):
        """创建AI演示数据"""
        self.print_section("创建AI智能化数据")
        
        # 创建智能推荐
        recommendations_data = [
            {
                'type': 'maintenance',
                'title': '建议对ThinkPad X1进行预防性维修',
                'description': '根据使用频率分析，该设备即将到达维修周期，建议提前安排维修。',
                'confidence': 85.5,
                'priority': 'high'
            },
            {
                'type': 'replacement',
                'title': '建议更换老化的打印机设备',
                'description': '该打印机使用年限较长，维修成本上升，建议考虑更换。',
                'confidence': 78.2,
                'priority': 'medium'
            },
            {
                'type': 'optimization',
                'title': '优化会议室投影仪的使用配置',
                'description': '检测到投影仪利用率较低，建议调整使用策略。',
                'confidence': 72.8,
                'priority': 'low'
            }
        ]
        
        for rec_data in recommendations_data:
            recommendation = AssetRecommendation.objects.create(
                user=random.choice(self.demo_data['users'][:2]),
                recommendation_type=rec_data['type'],
                title=rec_data['title'],
                description=rec_data['description'],
                asset=random.choice(self.demo_data['assets']),
                confidence_score=rec_data['confidence'],
                priority=rec_data['priority'],
                expires_at=timezone.now() + timedelta(days=30)
            )
            print(f"✓ 创建智能推荐: {recommendation.title}")
        
        # 创建异常检测
        anomalies_data = [
            {
                'type': 'usage_pattern',
                'description': '检测到异常的使用模式，与历史数据存在显著差异',
                'severity': 'medium',
                'confidence': 82.3
            },
            {
                'type': 'maintenance_frequency',
                'description': '维修频率异常，超出正常范围',
                'severity': 'high',
                'confidence': 91.7
            }
        ]
        
        for anomaly_data in anomalies_data:
            anomaly = AssetAnomalyDetection.objects.create(
                asset=random.choice(self.demo_data['assets']),
                anomaly_type=anomaly_data['type'],
                severity=anomaly_data['severity'],
                description=anomaly_data['description'],
                confidence_score=anomaly_data['confidence'],
                detection_algorithm='machine_learning'
            )
            print(f"✓ 创建异常检测: {anomaly.description}")
        
        # 创建利用率分析
        for asset in random.sample(self.demo_data['assets'], 3):
            analysis = AssetUtilizationAnalysis.objects.create(
                asset=asset,
                analysis_period_start=timezone.now() - timedelta(days=30),
                analysis_period_end=timezone.now(),
                utilization_rate=random.uniform(40, 85),
                idle_time_hours=random.uniform(100, 300),
                active_time_hours=random.uniform(200, 500),
                maintenance_time_hours=random.uniform(10, 50)
            )
            analysis.generate_suggestions()
            print(f"✓ 创建利用率分析: {asset.name} - {analysis.utilization_rate:.1f}%")
    
    def create_demo_system_data(self):
        """创建系统管理数据"""
        self.print_section("创建系统管理数据")
        
        # 创建系统日志
        log_data = [
            {'level': 'INFO', 'module': 'asset', 'action': 'create_asset', 'message': '创建新资产'},
            {'level': 'INFO', 'module': 'maintenance', 'action': 'complete_maintenance', 'message': '完成维修任务'},
            {'level': 'WARNING', 'module': 'inventory', 'action': 'low_stock_alert', 'message': '库存预警'},
        ]
        
        for log_item in log_data:
            SystemLog.objects.create(
                level=log_item['level'],
                module=log_item['module'],
                action=log_item['action'],
                message=log_item['message'],
                user=random.choice(self.demo_data['users'])
            )
            print(f"✓ 创建系统日志: {log_item['message']}")
        
        # 创建系统通知
        notifications_data = [
            {
                'title': '资产维修提醒',
                'message': '您有一台设备即将到达维修周期，请及时安排维修。',
                'type': 'warning',
                'priority': 'medium'
            },
            {
                'title': '盘点任务分配',
                'message': '您被分配了新的资产盘点任务，请及时完成。',
                'type': 'info',
                'priority': 'high'
            }
        ]
        
        for notif_data in notifications_data:
            notification = SystemNotification.objects.create(
                recipient=random.choice(self.demo_data['users'][2:]),
                title=notif_data['title'],
                message=notif_data['message'],
                notification_type=notif_data['type'],
                priority=notif_data['priority'],
                sender=self.demo_data['users'][1]
            )
            print(f"✓ 创建系统通知: {notification.title}")
    
    def display_system_overview(self):
        """显示系统概览"""
        self.print_section("系统数据概览")
        
        print(f"👥 用户数量: {User.objects.count()}")
        print(f"🏢 组织数量: {Organization.objects.count()}")
        print(f"🏬 部门数量: {Department.objects.count()}")
        print(f"📍 位置数量: {Location.objects.count()}")
        print(f"📦 资产类别: {AssetCategory.objects.count()}")
        print(f"🏭 供应商数量: {Supplier.objects.count()}")
        print(f"💼 资产总数: {Asset.objects.count()}")
        print(f"🔧 维修记录: {MaintenanceRecord.objects.count()}")
        print(f"📋 借用记录: {AssetBorrow.objects.count()}")
        print(f"🔄 调拨记录: {AssetTransfer.objects.count()}")
        print(f"📊 盘点计划: {InventoryPlan.objects.count()}")
        print(f"🤖 智能推荐: {AssetRecommendation.objects.count()}")
        print(f"⚠️ 异常检测: {AssetAnomalyDetection.objects.count()}")
        print(f"📈 利用率分析: {AssetUtilizationAnalysis.objects.count()}")
        print(f"📝 系统日志: {SystemLog.objects.count()}")
        print(f"🔔 系统通知: {SystemNotification.objects.count()}")
        print(f"⚙️ 系统参数: {SystemParameter.objects.count()}")
    
    def display_demo_accounts(self):
        """显示演示账户信息"""
        self.print_section("演示账户信息")
        
        print("🔐 演示账户 (密码: demo123456)")
        print("-" * 40)
        for user in self.demo_data.get('users', []):
            role = "超级管理员" if user.is_superuser else "管理员" if user.is_staff else "普通用户"
            print(f"👤 {user.username:10} | {user.first_name}{user.last_name:8} | {role}")
    
    def display_access_info(self):
        """显示访问信息"""
        self.print_section("系统访问信息")
        
        print("🌐 Web访问地址:")
        print("   主页: http://127.0.0.1:8000/")
        print("   管理后台: http://127.0.0.1:8000/admin/")
        print("   移动端扫码: http://127.0.0.1:8000/assets/mobile/scan/")
        
        print("\n📱 PWA功能:")
        print("   - 支持添加到主屏幕")
        print("   - 离线数据缓存")
        print("   - 后台数据同步")
        print("   - 推送通知")
        
        print("\n🔌 API接口:")
        print("   - 资产搜索: /assets/api/asset-search/")
        print("   - 资产列表: /assets/api/assets/")
        print("   - 通知管理: /assets/api/notifications/")
        print("   - 数据同步: /assets/api/sync/")
    
    def run_demo(self):
        """运行完整演示"""
        self.print_header("固定资产管理系统功能演示")
        
        print("🚀 正在创建演示数据...")
        
        # 创建演示数据
        self.create_demo_users()
        self.create_demo_organizations()
        self.create_demo_categories_and_assets()
        self.create_demo_business_data()
        self.create_demo_ai_data()
        self.create_demo_system_data()
        
        # 显示系统信息
        self.display_system_overview()
        self.display_demo_accounts()
        self.display_access_info()
        
        self.print_header("演示数据创建完成")
        
        print("✅ 演示数据已成功创建！")
        print("🎯 您现在可以使用以下功能进行体验：")
        print("   1. 资产管理 - 查看、编辑、分配资产")
        print("   2. 业务流程 - 借用、维修、调拨、盘点")
        print("   3. 智能推荐 - AI驱动的管理建议")
        print("   4. 移动应用 - PWA移动端体验")
        print("   5. 系统管理 - 参数配置、日志查看")
        
        print("\n🎉 开始您的固定资产管理系统体验之旅吧！")


if __name__ == '__main__':
    demo = SystemDemo()
    demo.run_demo()